#Include DrawData.ahk

class DrawMgr {

  _h := Map(), dd := DrawData(), _cur := ''

  __New(x, y, w, h) {
    this.canvas := ShinsOverlayClass(x, y, w, h, 1, 0, 0)
    this.pos := { x: x, y: y, w: w, h: h }
  }

  Register(which, handler) {
    if this._h.Has(which)
      throw Error('重复注册:' which)
    this._h.Set(which, handler)
    return this
  }

  Destroy() {
    this.canvas.gui.Destroy()
  }

  UseHandler(which, params*) {
    this._cur := which
    this.ins := this._h.Get(this._cur)(params*)
  }

  GetHandlerIns() => this.ins

  BeginDraw() {
    this.ins.BeginDraw(this.pos)
  }

  Draw() {
    this.canvas.BeginDraw()
    this.Render()
    this.ins.Draw(this.canvas, this.pos)
    this.canvas.EndDraw()
  }

  EndDraw() {
    if r := this.ins.EndDraw()
      this.dd.Push({ h: this._cur, data: r })
    this.dd.ClearUndo()
  }

  Undo(step := 1) {
    this.dd.Undo(step)
    this.canvas.BeginDraw()
    this.Render()
    this.canvas.EndDraw()
  }

  Redo(step := 1) {
    this.dd.Redo(step)
    this.canvas.BeginDraw()
    this.Render()
    this.canvas.EndDraw()
  }

  Render() {
    for v in this.dd._data {
      this._h.Get(v.h).render(this.canvas, v.data, this.pos)
    }
  }

  Move(x, y) {
    this.canvas.gui.Move(x, y)
    this.pos.x := x, this.pos.y := y
  }
}